package com.jukte.recipe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.ewhat.recipes.R;
import com.jukte.recipe.adapters.CartAdapter;
import com.jukte.recipe.adapters.CartAdapter.IndexPath;
import com.jukte.recipe.adapters.CartAdapter.SectionListAdapterAdapterDelegate;
import com.jukte.recipe.db.DataBaseManager;
import com.jukte.recipe.models.Ingredient;
import com.jukte.recipe.models.Recipe;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CartActivity extends ListActivity implements SectionListAdapterAdapterDelegate{
	ImageButton imb_search,imb_shoppingcart,imb_save,imb_add;
	TextView tv_title;

	private List<Recipe> cart_recipes;
	private List<List<Ingredient>> cart_ingredients;
	
	CartAdapter adapter;
	LayoutInflater inflater;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cart);
	
		init();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		new GetCartDataTask().execute();
	}
	
	
	public void init() {
		imb_search =(ImageButton)findViewById(R.id.imb_search);
		imb_shoppingcart =(ImageButton)findViewById(R.id.imb_shoppingcart);
		imb_save =(ImageButton)findViewById(R.id.imb_save);
		imb_add =(ImageButton)findViewById(R.id.imb_add);
		tv_title=(TextView)findViewById(R.id.textview_title_bar);
		tv_title.setSelected(true);
		
		imb_search.setVisibility(View.GONE);
		imb_shoppingcart.setVisibility(View.GONE);
		imb_add.setVisibility(View.VISIBLE);
		tv_title.setText("Shopping List");
		
		inflater = LayoutInflater.from(this);
		adapter = new CartAdapter();
        adapter.delegate = CartActivity.this;
        getListView().setAdapter(adapter);
        getListView().setOnItemClickListener(adapter.itemClickListener);
        
//        new GetCartDataTask().execute();
	}
	
	public void onClickAdd(View v)
	{ 
		if(cart_recipes.size()==0)
			Toast.makeText(this, "No recipe found!", Toast.LENGTH_SHORT).show();
		else{
			final CharSequence[] items=new CharSequence[cart_recipes.size()];
			for(int i=0;i<cart_recipes.size();i++)
				items[i]=cart_recipes.get(i).getName();
			new AlertDialog.Builder(this).setTitle("Add to recipe")
				.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialoginterface, int i) {
						Intent in=new Intent(CartActivity.this, AddMoreDialogActivity.class);
						in.putExtra("recipe_id", cart_recipes.get(i).getId());
						startActivity(in);
					}
				}).show();
		}
	}
	
	public void onClickDeleteAll(View v)
	{
		if(cart_recipes.size()==0)
			Toast.makeText(this, "No recipe found!", Toast.LENGTH_SHORT).show();
		else{
			Builder ad = new AlertDialog.Builder(CartActivity.this);
			ad.setTitle("Notice!");
			ad.setMessage("Are you sure want to delete All Recipes in cart?");
			ad.setCancelable(false);
			ad.setPositiveButton("Yes", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					for(int i=0;i<cart_recipes.size();i++)
					{
						Recipe re=cart_recipes.get(i);
						List<Ingredient> ins=cart_ingredients.get(i);
						for(int j=0;j<ins.size();j++)
							ins.get(j).setIsAddedToCart(0);
						DataBaseManager.getInstance().updateCart(re.getId(), 0, ins);
						
						List<Ingredient> custom_ins=cart_ingredients.get(i);
						custom_ins=DataBaseManager.getInstance().getCustomIngredients(re.getId());
						for(int j=0;j<custom_ins.size();j++)
							DataBaseManager.getInstance().deleteCustomIngredient(custom_ins.get(j));
					}
					DataBaseManager.getInstance().closeDb();
					new GetCartDataTask().execute();
				}
			});
			ad.setNegativeButton("No", null);
			ad.show();
		}
	}
	
	public void onClickEmailthis(View v)
	{ 
		if(cart_recipes.size()==0)
			Toast.makeText(this, "No recipe found!", Toast.LENGTH_SHORT).show();
		else{
			try {
				Calendar c = Calendar.getInstance();
				String message="Shopping cart ("+c.get(Calendar.MONTH)+"-"+c.get(Calendar.DAY_OF_MONTH)+"-"+c.get(Calendar.YEAR)+")\n";
				for(int i=0;i<cart_recipes.size();i++)
				{
					Recipe re=cart_recipes.get(i);
					message+="\n"+(i+1)+". "+re.getName();
					
					List<Ingredient> ins=new ArrayList<Ingredient>();
					ins=DataBaseManager.getInstance().getAllIngredients_in_Cart(re.getId());
					for(int j=0;j<ins.size();j++)
						message+="\n"+"  - "+ins.get(j).getText();
					message+="\n";
				}
				
		        final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		        emailIntent.setType("plain/text");
		        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "[I love Quinoa] Shopping cart");
		        emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
		        startActivity(Intent.createChooser(emailIntent, "Send mail..."));
		    } catch (ActivityNotFoundException e) {
		    	Toast.makeText(this, "No email apps found!", Toast.LENGTH_SHORT).show();
		    }
		}
	}
	
	@Override
	public int sectionCount() {
		try
		{
			if(cart_recipes!=null)
			{
				//Log.i("sectionCount", cart_recipes.size()+"");
				return cart_recipes.size();
			}
		}catch (Exception e) {}
		
		return 0;
	}


	@Override
	public int rowsInSection(int section) {
		try
		{
			if(cart_ingredients!=null){
				//Log.i("rowsInSection", cart_ingredients.get(section).size()+"");
				return cart_ingredients.get(section).size();
			}
		}catch (Exception e) {}
		return 0;
	}


	@Override
	public View viewForRowAtIndexPath(final IndexPath path) {
		View view = inflater.inflate(R.layout.row_cart_ingredient, null);
		TextView text = (TextView)view.findViewById(R.id.text);
		Button btn_delete=(Button)view.findViewById(R.id.img_delete);
		
		Ingredient ingredient=cart_ingredients.get(path.section).get(path.row);
		text.setText(ingredient.getText());
		btn_delete.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Ingredient in=cart_ingredients.get(path.section).get(path.row);
				if(in.getRecipe_id()==-1)
				{
					in.setIsAddedToCart(0);
					DataBaseManager.getInstance().updateCart(cart_recipes.get(path.section).getId(), 1, cart_ingredients.get(path.section));
				}
				else
				{
					DataBaseManager.getInstance().deleteCustomIngredient(in);
				}
				DataBaseManager.getInstance().closeDb();
				new GetCartDataTask().execute();
			}
		});
		Log.i("=====viewForRowAtIndexPath=====", ingredient.getText());
		return view;
	}


	@Override
	public View viewForHeaderInSection(final int section) {
		View view = inflater.inflate(R.layout.row_cart_recipe, null);
		TextView text = (TextView)view.findViewById(R.id.text);
		ImageView img_recipe=(ImageView)view.findViewById(R.id.img_reciepe);
		Button btn_delete=(Button)view.findViewById(R.id.img_delete);
		
		text.setText(cart_recipes.get(section).getName());
		
		int resId = getResources().getIdentifier("quinoa_menuicon","raw", getPackageName());
		
		
		Bitmap bmp = BitmapFactory.decodeFile(getFilesDir().getPath()+"/raw/"+cart_recipes.get(section).getImgPathThumnail());
		if(null != bmp){
			img_recipe.setImageBitmap(bmp);
		}else{
			img_recipe.setImageResource(resId);
		}
		
		btn_delete.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Builder ad = new AlertDialog.Builder(CartActivity.this);
				ad.setTitle("Notice!");
				ad.setMessage("Are you sure want to delete this recipe in cart?");
				ad.setCancelable(false);
				ad.setPositiveButton("Yes", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Recipe re=cart_recipes.get(section);
						List<Ingredient> ins=cart_ingredients.get(section);
						for(int i=0;i<ins.size();i++)
							ins.get(i).setIsAddedToCart(0);
						DataBaseManager.getInstance().updateCart(re.getId(), 0, ins);
						
						List<Ingredient> custom_ins=cart_ingredients.get(section);
						custom_ins=DataBaseManager.getInstance().getCustomIngredients(re.getId());
						for(int i=0;i<custom_ins.size();i++)
							DataBaseManager.getInstance().deleteCustomIngredient(custom_ins.get(i));
						
						DataBaseManager.getInstance().closeDb();
						new GetCartDataTask().execute();
					}
				});
				ad.setNegativeButton("No", null);
				ad.show();
			}
		});
		Log.i("=====viewForHeaderInSection=====", cart_recipes.get(section).getName());
		return view;
	}
	
	

	@Override
	public void itemSelectedAtIndexPath(IndexPath path) {
		
		/*int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(this, "Row " + path.row + " in section " + path.section + " selected", duration);
		toast.show();*/
		
	}
	
	//=================================================================
	
	private class GetCartDataTask extends AsyncTask<Void, Void, Void> 
    {
        public ProgressDialog progDialog=null;
        ArrayList<Recipe> temp_cart_recipes=new ArrayList<Recipe>();
        ArrayList<List<Ingredient>> temp_cart_ingredients=new ArrayList<List<Ingredient>>();
        
        protected void onPreExecute() 
        {
            progDialog=ProgressDialog.show(CartActivity.this, "", "Loading...",true);
        }
        @Override
        protected Void doInBackground(Void... params) 
        {
        	temp_cart_recipes.clear();
        	temp_cart_recipes.addAll(DataBaseManager.getInstance().getAllCartRecipeList());
    		
    		for(int i=0;i<temp_cart_recipes.size();i++)
    		{
    			ArrayList<Ingredient> ingredients=new ArrayList<Ingredient>();
    			ingredients.addAll(DataBaseManager.getInstance().getAllIngredients_in_Cart(temp_cart_recipes.get(i).getId()));
    			temp_cart_ingredients.add(ingredients);
    		}
            return null;
        }    
        protected void onPostExecute(Void result) 
        {
        	DataBaseManager.getInstance().closeDb();
            if(progDialog.isShowing()) progDialog.dismiss();
            
            cart_recipes=temp_cart_recipes;
            cart_ingredients=temp_cart_ingredients;
            
            adapter.notifyDataSetChanged();
        }
    }
}
